﻿using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using PortalWeb.Areas.Admin.Models;
using PortalWeb.Core.Entity;
using PortalWeb.Filter;
using PortalWeb.Models;
using PortalWeb.Common.UI;
using PortalWeb.Business.Manager;
using PortalWeb.Business.Entity;

namespace PortalWeb.Areas.Admin.Controllers
{
    [Navbar("用户管理", "系统管理")]
    [CustomAuthorize]
    public class UserController : Controller
    {
        private ApplicationRoleManager _roleManager;
        private ApplicationUserManager _userManager;

        public UserController()
        {
        }

        public ApplicationUserManager AppUserManager
        {
            get
            {
                return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
            }
            private set
            {
                _userManager = value;
            }
        }

        public ApplicationRoleManager AppRoleManager
        {
            get
            {
                return _roleManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationRoleManager>();
            
            }
            private set
            {
                _roleManager = value;
            }
        }
        /// <summary>
        /// 用户导航栏
        /// </summary>
        /// <returns>分部视图</returns>
        public ActionResult Menu()
        {
            return PartialView();
        }

        [Authorize(Roles = RoleConst.ADMINISTRATOR)]
        public ActionResult Index()
        {
            return View();
        }

        [CustomAuthorize]
        public async Task<JsonResult> List(string sort = "Id", string order = "", int offset = 0, int limit = 10,
            string search = "")
        {
            var model = from p in await AppUserManager.LoadPageEntitiesnAsync<ApplicationUserManager>(
                f => f.UserName.Contains(search) || f.NickName.Contains(search),
                order, sort, offset, limit)
                select new
                {
                    p.Id,
                    p.UserName,
                    p.Email,
                    p.PhoneNumber,
                    p.NickName,
                };
            return Json(new {total = AppUserManager.Users.Count(), rows = model},
                JsonRequestBehavior.AllowGet);
        }

        [Authorize(Roles = RoleConst.ADMINISTRATOR)]
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost, ActionName("Create")]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> CreateConfirmed(CreateUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUserModel
                {
                    UserName = model.UserName,
                    NickName = model.NickName,
                    Email = model.Email,
                    PhoneNumber = model.PhoneNumber
                };
                var result = await AppUserManager.CreateAsync(user);
                if (result.Succeeded)
                {
                    string url = Url.Action("Index");
                    return Json(new { success = true, url = url });
                    //return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }
            return View(model);
        }


        //
        // GEG: /Account/Edit
        [Authorize(Roles = RoleConst.ADMINISTRATOR)]
        public ActionResult Edit(string id,ManageMessageId? message = null)
        {
            var user = AppUserManager.Users.First(u => u.Id == id);
            var model = new EditUserViewModel(user);
            ViewBag.MessageId = message;
            return View(model);
        }



        //
        // POST: /Account/Edit
        [HttpPost]
        [Authorize(Roles = RoleConst.ADMINISTRATOR)]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Edit(EditUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUserModel
                {
                    Id =model.Id,
                    UserName = model.UserName,
                    PhoneNumber = model.PhoneNumber,
                    Email = model.Email,
                    NickName = model.Email,
                };
                var result = await AppUserManager.UpdateAsync(user);
                if (result.Succeeded)
                {
                    string url = Url.Action("Index");
                    return Json(new { success = true, url = url });
                    //return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }
            return View(model);
        }

        //
        // GEG: /Account/Delete
        [Authorize(Roles = RoleConst.ADMINISTRATOR)]
        public ViewResult Delete(string id, ManageMessageId? message)
        {
            var user =  AppUserManager.Users.First(u => u.Id == id);
            var model = new EditUserViewModel(user);
            return View(model);
        }
        //
        // POST: /Account/Delete
        [HttpPost, ActionName("Delete")]
        [Authorize(Roles = RoleConst.ADMINISTRATOR)]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> DeleteConfirmed(string id)
        {
            var user = await AppUserManager.Users.FirstAsync(u => u.Id == id);
            var result = await AppUserManager.DeleteAsync(user);
            if (result.Succeeded)
            {
                string url = Url.Action("Index");
                return Json(new {success = true, url = url});
            }
            AddErrors(result);
            var model = new EditUserViewModel(user);
            return View(model);
        }

        //
        // GEG: /Account/UserRoles
        [Authorize(Roles = RoleConst.ADMINISTRATOR)]
        public ActionResult UserRoles(string id)
        {
            var user = AppUserManager.Users.First(u => u.Id == id);
            var model = new SelectUserRolesViewModel(AppRoleManager,user);
            
            return View(model);
        }



        //
        // POST: /Account/UserRoles
        [HttpPost]
        [Authorize(Roles = RoleConst.ADMINISTRATOR)]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> UserRoles(SelectUserRolesViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = AppUserManager.Users.First(u => u.UserName == model.UserName);
                user.Roles.Clear();
                foreach (var role in model.Roles)
                {
                    if (role.Selected)
                    {
                        var roleItem = AppRoleManager.Roles.First(p => p.Name == role.RoleName);
                        user.Roles.Add(new IdentityUserRole {UserId = user.Id, RoleId = roleItem.Id});
                    }
                }
                var result = await AppUserManager.UpdateAsync(user);
                if (result.Succeeded)
                {
                    string url = Url.Action("Index");
                    return Json(new {success = true, url = url});
                    // return RedirectToAction("index");
                }
                AddErrors(result);
            }
            return View(model);
        }

        private bool HasPassword()
        {
            var user = AppUserManager.FindById(User.Identity.GetUserId());
            if (user != null)
            {
                return user.PasswordHash != null;
            }
            return false;
        }
        private void AddErrors(IdentityResult result)
        {
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError("", error);
            }
        }
	}

    public enum ManageMessageId
    {
        ChangePasswordSuccess,
        SetPasswordSuccess,
        RemoveLoginSuccess,
        Error
    }
}